package com.example.wm.controller;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.wm.common.R;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.entity.Wxaccesstken;
import com.example.wm.service.GetAceesstokenService;
import com.example.wm.utils.settoken;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

@Slf4j
@RestController
//小程序消息订阅和发布
@RequestMapping("/getaceess_token")
public class GetAccessTokenController {
    @Resource
    private GetAceesstokenService getAceesstokenService;

    @PostMapping("/updateaccess")
    public  void updateaccess(){
        settoken tos=new settoken();
         String  accesstoken=  tos.getToken();
        Wxaccesstken k=new Wxaccesstken();
        k.setId(1);
        k.setToken(accesstoken);
        getAceesstokenService.updateById(k);

    }
    //    发送微信模板消息
    @PostMapping("/wxtx")
    public Result wxtx(@RequestBody JSONObject jsonObject){
        String template_id= jsonObject.getString("template_id");
        String touser= jsonObject.getString("touser");
        Object data= jsonObject.getJSONObject("data");
        String name=jsonObject.getString("name");

        String lang= jsonObject.getString("lang");
        String miniprogram_state= jsonObject.getString("miniprogram_state");
        String result = null;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //响应模型
        CloseableHttpResponse res = null;
        String accessUrl = "https://api.weixin.qq.com/cgi-bin/token?appid=wxba6a21693d6b5a99&secret=836e5643d37955fbaa32894a8614c60e&grant_type=client_credential";
        //创建get请求
        HttpGet httpGet = new HttpGet(accessUrl);
        try {
            res = httpClient.execute(httpGet);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //获取响应实体
        HttpEntity responseEntity = res.getEntity();
        String resultDemo = null;
        try {
            resultDemo = EntityUtils.toString(responseEntity);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //转换成对象，好把需要的字段对应的值拿出来
        JSONObject json = JSONObject.parseObject(resultDemo);


       String access_token = json.getString("access_token");
try {



        String baseUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?" +
                "access_token=" + access_token

                ;
        HashMap<String, Object> requestParam = new HashMap<>();

        requestParam.put("template_id", template_id);
        requestParam.put("touser", touser);
        requestParam.put("data",  data);
        System.out.println(data);
        requestParam.put("miniprogram_state", miniprogram_state);
        if(Objects.equals(template_id, "dUBxBRSx0NpyiljBFec8tL5d5qHpLB9qrj8Gtbv_yZo")){
            requestParam.put("page", "subpkg/leave/approve/approve?name="+name);

        }else{
            requestParam.put("page", "pages/index/index");

        }

        requestParam.put("lang", lang);


        String jsonStr = JSONUtil.toJsonStr(requestParam);
    System.out.println(jsonStr);



        HttpResponse response = HttpRequest.post(baseUrl)
                .header(Header.CONTENT_ENCODING, "UTF-8")
                // 发送json数据需要设置contentType
                .header(Header.CONTENT_TYPE, "application/json")
                .body(jsonStr)
                .execute();
        if (response.getStatus() == HttpStatus.HTTP_OK) {
            result = response.body();
//            System.out.println(result);
        }
    }  catch (Exception e) {
        e.printStackTrace();
    }
        return ResultData.success(result);
    }
}
